package com.buss.purchase.controller;

import java.util.Date;
import java.util.Map;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.buss.base.model.Branch;
import com.buss.base.service.BranchService;
import com.buss.base.service.BussinessBillNoService;
import com.buss.core.controller.BaseController;
import com.buss.core.dic.BussinessBillNoType;
import com.buss.core.dic.CheckStatus;
import com.buss.core.dic.RecordStatus;
import com.buss.core.exception.ServiceException;
import com.buss.core.exception.WebException;
import com.buss.core.model.User;
import com.buss.core.persistence.OrderBy;
import com.buss.core.persistence.Pagination;
import com.buss.core.persistence.ResultList;
import com.buss.core.service.UserService;
import com.buss.core.sysparam.SysStaticParam;
import com.buss.core.utils.DateFormat;
import com.buss.core.utils.DateUtil;
import com.buss.core.utils.StringUtil;
import com.buss.purchase.model.PurchaseOrderDetail;
import com.buss.purchase.model.PurchaseOrderMaster;
import com.buss.purchase.model.PurchaseOrderMaster.ArriveStatus;
import com.buss.purchase.service.PurchaseOrderService;

@Controller
@RequestMapping("/admin/purchaseorder/")
public class PurchaseOrderController extends BaseController {

	/**采购订单号前缀*/
	private String PURCHASE_ORDERNUMBER_PREFIX = "CGDD";
	
	@Autowired
	private PurchaseOrderService orderService;
	
	@Autowired
	private BussinessBillNoService billNoService;
	
	/**库房管理*/
	@Autowired
	private BranchService branchService;
	
	/**用户信息*/
	@Autowired
	private UserService userService;
	
	@Override
	@RequestMapping("page")
	public ModelAndView listPage(String menuid) {
		ModelAndView view = new ModelAndView("purchaseorder/listpage");
		String createStartDate = DateUtil.getFirstDateOfMonth(new Date());
		String createEndDate = DateUtil.getCurrentDateStr();
		view.addObject("createStartDate", createStartDate);
		view.addObject("createEndDate", createEndDate);
		view.addObject(SysStaticParam._MENUID_NAME, menuid);
		return view;
	}

	/**
	 * 编辑采购订单页面
	 */
	@RequestMapping("{type}")
	public ModelAndView editPage(@PathVariable String type, Long id,HttpServletRequest request) throws WebException{
		ModelAndView view = new ModelAndView("purchaseorder/edit");
		PurchaseOrderMaster orderMaster = new PurchaseOrderMaster();
		orderMaster.setBranch(getBranch(request));
		ResultList<Branch> branchs = branchService.queryBranchByRole(getUserRoleIds(request), RecordStatus.normal, null);
		ResultList<User> users = userService.queryUserBySales(getCompanyId(request), true);
		if(EDIT_PAGE.equals(type)){
			orderMaster = orderService.loadOrderMaster(id);
			if(!orderMaster.getCheckStatus().equals(CheckStatus.untreated) 
					&& !orderMaster.getCheckStatus().equals(CheckStatus.notAudited)){
				throw new WebException("只能修改状态为未处理和未通过的订单信息!");
			}
		}		
		view.addObject("type", type);
		view.addObject("branchs",branchs.getData());
		view.addObject("users", users.getData());
		view.addObject("orderMaster", orderMaster);
		return view;
	}

	/**
	 * 删除采购订单
	 */
	@Override
	@RequestMapping("delMaster")
	@ResponseBody
	public Map<String, Object> delete(Long[] ids) throws WebException {
		try{
			orderService.removeOrderMaster(ids[0]);
		}catch(ServiceException ex){
			throw new WebException(ex.getMessage());
		}
		return SysStaticParam.resultMessage("删除采购订单信息成功!");
	}

	/**
	 * 新增采购订单信息
	 * @param orderMaster
	 * @param request
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public Map<String, Object> add(PurchaseOrderMaster orderMaster,HttpServletRequest request)
		throws WebException{
		orderMaster.getBranch().setCompanyId(getCompanyId(request));
		orderMaster.setCheckStatus(CheckStatus.untreated);
		orderMaster.setCreateUserId(getUser(request).getId());
		orderMaster.setCreateUserName(getUser(request).getUserName());
		orderMaster.setCreateDate(new Date());
		orderMaster.setIsArrive(ArriveStatus.notArrive);
		if(StringUtil.isEmpty(orderMaster.getOrderNumber())){
			orderMaster.setOrderNumber(billNoService.genBillNoVal(PURCHASE_ORDERNUMBER_PREFIX, getCompanyId(request), BussinessBillNoType.purchorder));
		}
		try{
			orderMaster = orderService.saveOrderMaster(orderMaster);
		}catch(PersistenceException e){
			throw new WebException(e.getMessage());
		}
		Map<String, Object> map = SysStaticParam.resultMessage("新增采购订单信息成功!");
		map.put("orderMaster", orderMaster);
		return map;
	}
	
	/**
	 * 修改采购订单信息
	 * @param orderMaster
	 * @param request
	 * @return
	 */
	@RequestMapping("editMaster")
	@ResponseBody
	public Map<String, Object> edit(PurchaseOrderMaster orderMaster,Long[] removeDetailIds,HttpServletRequest request)
	 	throws WebException{
		orderMaster.getBranch().setCompanyId(getCompanyId(request));
		if(StringUtil.isEmpty(orderMaster.getOrderNumber())){
			orderMaster.setOrderNumber(billNoService.genBillNoVal(PURCHASE_ORDERNUMBER_PREFIX, getCompanyId(request), BussinessBillNoType.purchorder));
		}
		try{
			orderService.editOrderMaster(orderMaster,removeDetailIds);
		}catch(PersistenceException e){
			throw new WebException(e.getMessage());
		}
		return SysStaticParam.resultMessage("修改采购订单信息成功!");
	}
	
	/**
	 * 更新采购订单审核状态
	 * @param id
	 * @param status
	 * @param request
	 * @return
	 */
	@RequestMapping("check")
	@ResponseBody
	public Map<String,Object> updateCheckStatus(Long id,CheckStatus status,HttpServletRequest request){
		if(status.equals(CheckStatus.audited) || status.equals(CheckStatus.notAudited)){
			orderService.updateCheckStatus(id, status, getUser(request).getId(), getUser(request).getUserName(), new Date());
		}else{
			orderService.updateCheckStatus(id, status, null, null, null);
		}
		return SysStaticParam.resultMessage("更新审核状态成功!");
	}
	
	/**
	 * 获取采购订单信息列表
	 * @param companyId	单位编码
	 * @param supplierId	供应商编码
	 * @param branchId	库房编码
	 * @param salesManId	业务员ID
	 * @param orderStartDate	订单开始时间
	 * @param orderEndDate	订单结束时间
	 * @param checkStatus	审核状态
	 * @param checkUserId	审核人
	 * @param checkStartDate	审核开始时间
	 * @param checkEndDate		审核结束时间
	 * @param createUserId	录入人
	 * @param createStartDate	录入开始时间
	 * @param createEndDate	录入结束时间
	 * @param page	
	 * @param orderField	排序属性
	 * @param orderType	排序类型(asc升序,desc降序)
	 * @return
	 */
	@RequestMapping("listMaster")
	@ResponseBody
	public Map<String, Object> listMaster(Long branchId,Long supplierId,
			Long salesManId,Date orderStartDate,Date orderEndDate,CheckStatus checkStatus,
			Long checkUserId,Date checkStartDate,Date checkEndDate,Long createUserId,
			Date createStartDate,Date createEndDate,@ModelAttribute Pagination page,String orderField,String orderType,HttpServletRequest request){
		OrderBy orderBy = null;
		if(StringUtil.isNotEmpty(orderField)){
			orderBy = new OrderBy();
			orderBy.add(orderField, orderType);
		}
		ResultList<PurchaseOrderMaster> rs = orderService.queryOrderMaster(getCompanyId(request),supplierId, branchId, salesManId, orderStartDate, orderEndDate, checkStatus, checkUserId, checkStartDate, checkEndDate, createUserId, createStartDate, createEndDate, page, orderBy);
		Map<String, Object> map = SysStaticParam.resultMessage("获取采购订单信息列表成功!");
		map.put(SysStaticParam._RESULT, rs);
		return map;
	}
	
	/**
	 * 获取采购订单明细信息(用于编辑订单)
	 * @param masterId
	 * @return
	 */
	@RequestMapping("queryOrderDetailForEdit/{masterId}")
	@ResponseBody
	public Map<String, Object> queryOrderDetailForEdit(@PathVariable Long masterId,Long goodsId,@ModelAttribute Pagination page){
		ResultList<PurchaseOrderDetail> rs = orderService.queryOrderDetail(masterId, null, goodsId, page);
		Map<String, Object> map = SysStaticParam.resultMessage("获取采购订单明细信息成功!");
		map.put(SysStaticParam._RESULT, rs);
		return map;
	}
	
	

	@InitBinder
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception{
		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(new DateFormat(DateUtil.FORMAT_DATE), true));
	}
	
	public static void main(String[] args){
		for (CheckStatus status : CheckStatus.values()) {
			System.out.println(status + "----" + status.getValue());
		}
	}
}
